package com.demo.controls;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.common.model.Shoppingcar;
import com.jfinal.kit.JsonKit;

/**
 * IndexController
 */
public class ShoppingCarController extends BaseController {
	public void index() {
		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}

		List<Shoppingcar> resultList = Shoppingcar.dao.find(
				"select * from shoppingcar where fuserid = ? ", userid);
		
		JSONArray ja = JSONArray.parseArray(JsonKit.toJson(resultList));
		for (int i = 0; i < ja.size(); i++) {
			JSONObject jsonObject = ja.getJSONObject(i);
			jsonObject.put("goods",getGoods(jsonObject.getIntValue("fgoodsid")));
		}
		renderJson(ja.toString());
		
		return;
	}

	public void add() {
		String paraArray = getPara("goodsid");
		if (paraArray == null) {
			renderErr("goodsid==null");
			return;
		}
		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}

		int[] temp = getParToIntArray(paraArray);
		if (temp == null) {
			renderErr("goodsid parse err");
			return;
		}
		for (int i = 0; i < temp.length; i++) {
			Shoppingcar shoppingcar = new Shoppingcar();
			shoppingcar.setFuserid(userid);
			shoppingcar.setFgoodsid(temp[i]);
			shoppingcar.save();
		}
		renderOK();
	}

	public void remove() {
		int userid;
		if ((userid = checkToken()) < 0) {
			return;
		}
		String paraArray = getPara("goodsid");
		if (paraArray == null) {
			renderErr("goodsid==null");
			return;
		}

		int[] temp = getParToIntArray(paraArray);
		if (temp == null) {
			renderErr("goodsid parse err");
			return;
		}
		for (int i = 0; i < temp.length; i++) {
			List<Shoppingcar> users = Shoppingcar.dao
					.find("select * from shoppingcar where fuserid = ? and fgoodsid = ?",
							userid, temp[i]);
			for (int j = 0; j < users.size(); j++) {
				users.get(j).delete();
			}
		}
		renderOK();
	}
}